package com.ruoyi.project.rate.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.framework.web.service.CrudService;
import com.ruoyi.project.rate.Constants;
import com.ruoyi.project.rate.domain.Cp;
import com.ruoyi.project.rate.domain.CpDetail;
import com.ruoyi.project.rate.mapper.CpMapper;

@Service
public class CpService extends CrudService<CpMapper, Cp> {
	@Autowired
	private CpMapper cpMapper;
    @Autowired
    private CpDetailService cpDetailService;

    @Transactional(readOnly = false)
    public int save(Cp cp, List<CpDetail> cpDetailList) {
        // 查询数据库中已有的数据，准备删除
        Map<String, CpDetail> detailMap = new HashMap<String, CpDetail>();

        if (StringUtils.isNotBlank(cp.getId())) {
            CpDetail detail = new CpDetail();
            detail.setCp(cp);
            List<CpDetail> details = this.cpDetailService.findList(detail);
            for (CpDetail d : details) {
                detailMap.put(d.getId(), d);
            }
        }
        
        cp.setStatus(Constants.CP_STATUS_DRAFT);
        int i = super.save(cp);

        for (CpDetail detail : cpDetailList) {
            detail.setCp(cp);
            this.cpDetailService.save(detail);
            detailMap.remove(detail.getId());
        }

        for (CpDetail detail : detailMap.values()) {
            this.cpDetailService.delete(detail);
        }

        return i;
    }
    
    @Transactional(readOnly = false)
    public int updateStatus(Cp cp) {
        return this.cpMapper.updateStatus(cp);
    }
}
